package com.itheima.service.mongo.Impl;

import cn.hutool.core.collection.CollectionUtil;
import com.itheima.domain.mongo.UserLocation;
import com.itheima.service.mongo.UserLocationService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;

@DubboService
public class UserLocationServiceImpl implements UserLocationService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override//经度纬度
    public void saveOrUpdateLocation(String longitude, String latitude, String addrStr, Long userId) {
        Query query = new Query(Criteria.where("userId").is(userId));
        UserLocation userLocation = mongoTemplate.findOne(query, UserLocation.class);
        UserLocation newLocation = new UserLocation();
//new 一个新的直接用于保存
        newLocation.setUserId(userId);
        newLocation.setLocation(new GeoJsonPoint(Double.valueOf(longitude), Double.valueOf(latitude)));
        newLocation.setAddress(addrStr);
        newLocation.setLastUpdated(System.currentTimeMillis());
        if (userLocation == null) {
            newLocation.setCreated(System.currentTimeMillis());
        }else {
            //如果有记录执行修改操作
            newLocation.setId(userLocation.getId());
            newLocation.setCreated(userLocation.getCreated());
        }
        mongoTemplate.save(newLocation);
    }

    @Override
    public List<Long> searchNearUser(Long userId, Long distance) {
        Query query = new Query(Criteria.where("userId").is(userId));
        UserLocation userLocation = mongoTemplate.findOne(query, UserLocation.class);

        GeoJsonPoint location = userLocation.getLocation();
        Distance dis= new Distance(distance, Metrics.KILOMETERS);//TODO 后续distance需要除以1000
        System.out.println("searchNearUser--distance"+distance);
        System.out.println("searchNearUser--userId"+userId);
        Circle circle = new Circle(location, dis);
        Query query1 = new Query(Criteria.where("location").withinSphere(circle));
        List<UserLocation> userLocations = mongoTemplate.find(query1, UserLocation.class);
        //只需要返回需要的id的集合
        List<Long> ids = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(userLocations)){
            for (UserLocation userLocation1 : userLocations) {
                System.out.println("searchNearUser---userLocation1---"+userLocation1);
                ids.add(userLocation1.getUserId());

            }
        }
        return ids;
    }
}
